<template>
  <div class="history-list">
    <ul>
      <li v-for="(record, index) in history" :key="index" @click="select(record, index)"
          :class="{ selected: selectedIndex === index }">
        <div class="record-content">
          <div id="pad_lef" class="truncate">{{ record.title }}</div>
          <el-tooltip class="item" effect="dark" content="选项" placement="top" popper-class="tooltip-width">
            <el-popover placement="bottom" trigger="click" popper-class="el-popover-self" ref="popover">
              <div class="popover-content">
                <el-button type="text" @click="open" class="popover-item">
                  <img src="../assets/photo/history/rewrite.png" alt="" class="user_img"><span class="user_word">重命名</span>
                </el-button>
                <el-button type="text" @click="deleteRecord(record.chatid, index)" class="popover-item">
                  <img src="../assets/photo/history/delete.png" alt="" class="user_img"><span class="user_word">删除</span>
                </el-button>
              </div>
              <img src="../assets/photo/history/dot.png" alt="" class="dot" slot="reference">
            </el-popover>
          </el-tooltip>
        </div>
      </li>
    </ul>
    <div id="occupation" v-if="is_phone"></div>
  </div>
</template>
<script>
import { deleteChat } from '../api/history/deleteSession';
import { updateTheme } from '@/api/main/updateTheme';

export default {
  name: 'HistoryList',
  props: ['history'],
  data() {
    return {
      selectedIndex: null,
      chatid: null,
    };
  },
  computed: {
    is_phone() {
      const userAgent = navigator.userAgent.toLowerCase();
      return /mobile|tablet|ip(ad|hone|od)|android/i.test(userAgent);
    }
  },
  methods: {
    // 选择记录
    select(record, index) {
      this.selectedIndex = index;
      this.chatid = record.chatid;
      this.$emit('select', record); // 将整个记录传递给父组件
    },

    // 清除选中的记录
    clearSelection() {
      this.selectedIndex = null;
    },

    // 获得当前是否有选中的记录
    hasSelected() {
      return this.selectedIndex !== null;
    },

    // 重命名记录
    async open() {
      this.$prompt('重命名:', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(async ({ value }) => {
        try {
          await updateTheme(this.chatid, value); // 调用API接口更新主题
        } catch (error) {
          console.error("Failed to update theme:", error);
          this.$message.error("重命名失败，请重试");
          return;
        }
        this.history[this.selectedIndex].title = value;
        this.$message({
          type: 'success',
          message: '重命名成功'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消重命名'
        });
      });
    },

    // 删除记录
    async deleteRecord(chatid, index) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const response = await deleteChat(chatid); // 调用API接口删除会话
        if (response.status === "200") {
          this.history.splice(index, 1); // 从历史记录中删除该记录
          this.selectedIndex = null;
          this.$emit('deleteRecord'); // 通知父组件删除成功
          this.$message({
            type: 'success',
            message: '删除成功'
          });
        } else {
          this.$message({
            type: 'error',
            message: '删除记录失败'
          });
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
  },
};
</script>
<style>
.history-list {
  width: 200px;
  height: 100vh;
  overflow-y: auto;
  border-right: 1px solid #ccc;
  padding: 0 !important;
  box-sizing: border-box;
}

.history-list ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.history-list li {
  text-align: left;
  font-size: 1.3vw;
  padding: 1.5vh 0;
  cursor: pointer;
}

.history-list li:hover, .history-list li.selected {
  background-color: #f0f0f0;
}

.record-content {
  display: flex;
  align-items: center;
}

#occupation {
  height: 0; /* 默认高度为0 */
}

#pad_lef {
  padding-left: 2vw;
  flex-grow: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.dot {
  width: 1.5vw;
  height: auto;
  padding-right: .6vw;
  position: relative;
  cursor: pointer;
  top: .2vh;
  left: .3vw;
}

.popover-content {
  display: flex;
  flex-direction: column;
}

.tooltip-width {
  width: 2.3vw;
  height: .5vw;
  font-size: 1.1vw !important;
  display: flex;
  justify-content: center;
  align-items: center;
}

.el-popover-self {
  width: 8vw !important;
  min-width: 20px !important;
  padding: 0;
}

.el-popover {
  padding: 0 !important;
}

.el-message-box {
  border-radius: 15px !important;
}

.el-button--text {
  color: black !important;
  border-radius: 0 !important;
}

.el-button+.el-button {
  margin-left: 0 !important;
}

button.el-button.el-button--default.el-button--small {
  margin-right: 10px !important;
}

.el-button--text:hover {
  background-color: #f0f0f0 !important;
}

.el-popper[x-placement^=bottom] {
  margin-top: 5px !important;
}

@media (max-width: 768px) {
  .tooltip-width {
    width: 4vw;
    height: .5vw;
    font-size: 1.9vw !important;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  #occupation {
    height: calc(85px + 7vh); /* 手机端的高度 */
  }

  .history-list li {
    font-size: 2.8vw;
  }

  .record-content {
    display: flex;
    align-items: flex-start;
  }

  .dot {
    width: 3vw;
    height: auto;
    padding-right: 2.5vw;
  }

  .el-message-box {
    border-radius: 15px !important;
    width: 300px !important;
    top: 50% !important;
  }

  .el-popover-self {
    width: 8vw !important;
    min-width: 100px !important;
    padding: 0;
  }
}
</style>
